import axios from 'axios';
import config from "../../config/config";

// 登录请求方法
const loginreq = (method, url, params) => {
  return axios({
    method: method,
    url: url,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    data: params,
    traditional: true,
    transformRequest: [
      function (data) {
        let ret = ''
        for (let it in data) {
          ret +=
            encodeURIComponent(it) +
            '=' +
            encodeURIComponent(data[it]) +
            '&'
        }
        return ret
      }
    ]
  }).then(res => res.data);
};
// 通用公用方法
const req = (method, url, params) => {
  return axios({
    method: method,
    url: url,
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      "x-token": localStorage.getItem('x-token')
    },
    data: JSON.stringify(params),
    // traditional: true
    // transformRequest: [
    //     function(data) {
    //         let ret = ''
    //         for (let it in data) {
    //             ret +=
    //                 encodeURIComponent(it) +
    //                 '=' +
    //                 encodeURIComponent(data[it]) +
    //                 '&'
    //         }
    //         return ret
    //     }
    // ]
  }).then(res => {
    return res.data
  }).catch(err => {
    if (err.response.status == 401 && !config.isLogin) {
      config.isLogin = true;
      window.location.href = "http://127.0.0.1:10002/system/sso/login?back=" + window.location.href;
    }
  });
};

export {
  loginreq,
  req
}
